package com.alt.ui;

import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.alt.R;
import com.alt.base.ALTBaseActivity;
import com.alt.connector.RestClient;
import com.alt.handler.CMCmdHandler;
import com.alt.manager.ALTAppMgr;
import com.alt.manager.ALTPTCMgr;
import com.alt.models.AdsInfo;
import com.alt.models.ImageModel;
import com.alt.models.TransactionData;
import com.alt.shared.IServiceCommandResult;
import com.alt.utils.ALTSysUtils;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;

public class ALTViewImage extends ALTBaseActivity implements IServiceCommandResult{

	private static final String STATE_POSITION = "STATE_POSITION";
	
	protected ImageLoader imageLoader = ImageLoader.getInstance();

	private DisplayImageOptions options;

	private ViewPager pager;
	
	private ImageModel imgmodel;
	
	private String fee = "0";
	
	private List<String> imgislst = new ArrayList<String>();
	
	private int currentPage = 0;	
	private boolean viewall = false;
	
	String service_url = "common/getfilestream/%s";

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ac_image_pager);
		
//		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
		
		Intent i = getIntent();
		imgmodel = (ImageModel) i.getExtras().getSerializable("ImageModel");
		fee = i.getExtras().getString("Fee");
		
	        if(!imgmodel.Img1.isEmpty()){	        	
	        	imgislst.add(RestClient.apiUrl(ALTSysUtils.format(service_url, imgmodel.Img1)));
	        }
	        if(!imgmodel.Img2.isEmpty()){
	        	imgislst.add(RestClient.apiUrl(ALTSysUtils.format(service_url, imgmodel.Img2)));
	        }
	        if(!imgmodel.Img3.isEmpty()){
	        	imgislst.add(RestClient.apiUrl(ALTSysUtils.format(service_url, imgmodel.Img3)));
	        }
	        if(!imgmodel.Img4.isEmpty()){
	        	imgislst.add(RestClient.apiUrl(ALTSysUtils.format(service_url, imgmodel.Img4)));
	        }
	        if(!imgmodel.Img5.isEmpty()){
	        	imgislst.add(RestClient.apiUrl(ALTSysUtils.format(service_url, imgmodel.Img5)));
	        }
	        
			String[] imageUrls =  imgislst.toArray(new String[imgislst.size()]);//IMAGES
			int pagerPosition = 0;

		imageLoader.init(ImageLoaderConfiguration.createDefault(this));
		options = new DisplayImageOptions.Builder()
			.showImageForEmptyUri(R.drawable.ic_empty)
			.showImageOnFail(R.drawable.ic_error)
			.resetViewBeforeLoading(true)
			.cacheOnDisc(true)
			.imageScaleType(ImageScaleType.EXACTLY)
			.bitmapConfig(Bitmap.Config.RGB_565)
			.displayer(new FadeInBitmapDisplayer(300))			
			.build();

		pager = (ViewPager) findViewById(R.id.pager);
		pager.setAdapter(new ImagePagerAdapter(imageUrls));
		pager.setCurrentItem(pagerPosition);
//		pager.setOffscreenPageLimit(1);
		
		pager.setOnPageChangeListener(new OnPageChangeListener() {						
			public void onPageSelected(int arg0) {
				// TODO Auto-generated method stub
				//Toast.makeText(ALTViewImage.this, String.valueOf(arg0), Toast.LENGTH_SHORT).show();
				currentPage = arg0;
				if (currentPage == imgislst.size() - 1) {
					viewall = true;
				}
			}
			
			public void onPageScrolled(int arg0, float arg1, int arg2) {
				// TODO Auto-generated method stub			
			}			
			
			public void onPageScrollStateChanged(int arg0) {
				// TODO Auto-generated method stub				
			}
		});
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		outState.putInt(STATE_POSITION, pager.getCurrentItem());
	}

	private class ImagePagerAdapter extends PagerAdapter {

		private String[] images;
		private LayoutInflater inflater;

		ImagePagerAdapter(String[] images) {
			this.images = images;
			inflater = getLayoutInflater();
		}

		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
			((ViewPager) container).removeView((View) object);
		}

		@Override
		public void finishUpdate(View container) {
		}

		@Override
		public int getCount() {
			return images.length;
		}

		@Override
		public Object instantiateItem(ViewGroup view, int position) {
			View imageLayout = inflater.inflate(R.layout.item_pager_image, view, false);
			ImageView imageView = (ImageView) imageLayout.findViewById(R.id.image);
			final ProgressBar spinner = (ProgressBar) imageLayout.findViewById(R.id.loading);
			
			Log.e("ALTViewImage Log:", String.valueOf(position));
			imageLoader.displayImage(images[position], imageView, options, new SimpleImageLoadingListener() {
				@Override
				public void onLoadingStarted(String imageUri, View view) {
					spinner.setVisibility(View.VISIBLE);
				}

				@Override
				public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
					String message = null;
/*					switch (failReason.getType()) {
						case IO_ERROR:
							message = "Input/Output error";
							break;
						case DECODING_ERROR:
							message = "Image can't be decoded";
							break;
						case NETWORK_DENIED:
							message = "Downloads are denied";
							break;
						case OUT_OF_MEMORY:
							message = "Out Of Memory error";
							break;
						case UNKNOWN:
							message = "Unknown error";
							break;
					}
					Toast.makeText(ALTViewImage.this, message, Toast.LENGTH_SHORT).show();*/

					spinner.setVisibility(View.GONE);
				}

				@Override
				public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
					spinner.setVisibility(View.GONE);
					
					
				}
			});

			((ViewPager) view).addView(imageLayout, 0);
			return imageLayout;
		}

		@Override
		public boolean isViewFromObject(View view, Object object) {
			return view.equals(object);
		}

		@Override
		public void restoreState(Parcelable state, ClassLoader loader) {
		}

		@Override
		public Parcelable saveState() {
			return null;
		}

		@Override
		public void startUpdate(View container) {
		}
	}	

	public void showDialogConfirm(final Context context, final String message) {
		AlertDialog.Builder builder = new Builder(context);
		builder.setTitle(getString(R.string.title_activity_main));
		builder.setMessage(message).setNeutralButton(getString(R.string.txt_btn_ok), new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {   
				
				if(viewall){//update transaction
					TransactionData trans = new TransactionData();
					trans.AdsId = imgmodel.AdsID;
					trans.TransGroupId = ALTPTCMgr.TRANSACTION_TYPE.CLICK.toString();
					trans.UserId = ALTAppMgr.getInstance().getUserLogInfo().UserId;
					trans.UserFee = fee;
					
					Bundle b = new Bundle();
					b.putSerializable(ALTPTCMgr.REST_OBJECT_PUT, trans);
					
					ALTAppMgr.getInstance().startServiceCmd(CMCmdHandler.COMMAND_UPDATE_TRANSACTION,new CMCmdHandler(), b,true);
					
				}else{//just close images slide
					imageLoader.clearMemoryCache();
					imageLoader.clearDiscCache();
					imageLoader.stop();
					finish();
				}
			}
		});
		builder.setPositiveButton(getString(R.string.txt_btn_cancel), new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface arg0, int arg1) {
				arg0.dismiss();
			}
		});
		AlertDialog alert = builder.create();
		alert.setCancelable(false);
		alert.setCanceledOnTouchOutside(false);
		alert.show();
	}
	
	@SuppressWarnings("unused")
	@Override
	public void processCommandResult(int commandCode, Object resultData) {
		// TODO Auto-generated method stub
		super.processCommandResult(commandCode, resultData);
		
		Bundle bResult = (Bundle) resultData;

		switch(commandCode){		
		     
		 case CMCmdHandler.COMMAND_UPDATE_TRANSACTION:{
			 String result = bResult.getString(ALTPTCMgr.REST_OBJECT_RETURN);	
			 result = result.replace("\"","");				 	
			
			 if(result.equals("1")){
				 //update current temporary ads list
				 List<AdsInfo> temp = ALTAppMgr.getInstance().getAdsLstData();
				 List<AdsInfo> tempclone = new ArrayList<AdsInfo>();				 
				 
				 for (AdsInfo adsInfo : temp) {
					if(!adsInfo.AdsID.equals(imgmodel.AdsID)){	
						tempclone.add(adsInfo);
					}
				 }
				 ALTAppMgr.getInstance().setAdsLstData(tempclone);
				 ALTAppMgr.getInstance().setAllow2Loadmore(true);
				 
				 //update new total user fee
				 ALTAppMgr.getInstance().getUserLogInfo().TotalUserFee = String.valueOf(Integer.parseInt(ALTAppMgr.getInstance().getUserLogInfo().TotalUserFee) + Integer.parseInt(fee));
			 }
			 
			AlertDialog.Builder alert = new AlertDialog.Builder(this.getParent() == null ? this : this.getParent());
			alert.setMessage(result.equals("1") ? R.string.txt_update_success : R.string.txt_update_fail);
			alert.setPositiveButton(R.string.txt_btn_ok,new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog,int id) {
					finish();
				}
			  });
			alert.show();
		 }
		    break;
		 
		 default:
			 break;		
		}			
	}
	
	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		
		if (currentPage == imgislst.size() - 1 || viewall) {
			viewall = true;
			showDialogConfirm(this, getString(R.string.msg_tks_user));
		}else{//To ask There is money if leaves
			showDialogConfirm(this, getString(R.string.msg_ask_close));
		}		
	}
	
	
	public String[] IMAGES = new String[] {
			"http://digipay.vn:8080/CommonSvc/common/getfilestream/2",
			"http://digipay.vn:8080/CommonSvc/common/getfilestream/3",	
			"http://digipay.vn:8080/CommonSvc/common/getfilestream/4",
			"http://digipay.vn:8080/CommonSvc/common/getfilestream/5",
			"http://digipay.vn:8080/CommonSvc/common/getfilestream/6"
};

}